package com.siteseat.common.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.io.IOUtils;

import com.siteseat.common.exception.InternalException;

/**
 * 支持SHA-1/MD5消息摘要的工具类. 支持Hex与Base64两种编码方式.
 */
public class Sha1Digest {

  private static final ThreadLocal<MessageDigest> MD = new ThreadLocal<MessageDigest>() {
                                                       @Override
                                                       protected MessageDigest initialValue() {
                                                         try {
                                                           return MessageDigest.getInstance( "SHA-1" );
                                                         } catch( NoSuchAlgorithmException e ) {
                                                           throw new InternalException( e );
                                                         }
                                                       }
                                                     };

  /**
   * 对字符串进行散列
   * 
   * @param input
   * @return bytes
   */
  public static byte[] digest( String input ) {
    MessageDigest messageDigest = MD.get();
    return messageDigest.digest( input.getBytes() );
  }

  /**
   * @param f
   * @return
   * @throws IOException
   */
  public static byte[] digest( File f ) throws IOException {
    InputStream fis = new FileInputStream( f );
    try {
      return digest( fis );
    } finally {
      IOUtils.closeQuietly( fis );
    }
  }

  /**
   * 对文件进行散列
   */
  public static byte[] digest( InputStream input ) throws IOException {
    MessageDigest messageDigest = MD.get();
    int bufferLength = 8000;
    byte[] buffer = new byte[bufferLength];
    int read = input.read( buffer, 0, bufferLength );

    while( read > -1 ) {
      messageDigest.update( buffer, 0, read );
      read = input.read( buffer, 0, bufferLength );
    }

    return messageDigest.digest();
  }
}
